import { View, Text, Image } from '@tarojs/components'
import { useState } from 'react'
import { AtIcon } from 'taro-ui'
import classNames from 'classnames'
import dayjs from 'dayjs'
import styles from './index.less'
import expandDown from '@/assets/icon/expand-down.png';

interface CalendarProps {
  selectedDate: string
  onDateSelect: (date: string) => void
}

interface DayItem {
  date: string,
  day: string,
  weekday?: string,
  isToday: boolean,
  isSelected: boolean,
  isCurrentMonth?: boolean,
}

const Calendar: React.FC<CalendarProps> = ({ selectedDate, onDateSelect }) => {
  const [expanded, setExpanded] = useState(false)
  const [currentMonth, setCurrentMonth] = useState(dayjs())

  // 生成周视图数据
  const generateWeekDays = () => {
    const days: DayItem[] = []
    const today = dayjs()
    const startDay = today.subtract(today.day() - 1, 'day') // 从周一开始

    for (let i = 0; i < 7; i++) {
      const currentDay = startDay.add(i, 'day')
      days.push({
        date: currentDay.format('YYYY-MM-DD'),
        day: currentDay.format('DD'),
        weekday: currentDay.format('dd').toUpperCase(),
        isToday: currentDay.isSame(today, 'day'),
        isSelected: currentDay.format('YYYY-MM-DD') === selectedDate
      })
    }
    return days
  }

  // 生成月视图数据
  const generateMonthDays = () => {
    const days: DayItem[] = []
    const firstDay = currentMonth.startOf('month')
    const startDay = firstDay.subtract((firstDay.day() + 6) % 7, 'day') // 从周一开始

    for (let i = 0; i < 42; i++) {
      const currentDay = startDay.add(i, 'day')
      days.push({
        date: currentDay.format('YYYY-MM-DD'),
        day: currentDay.format('DD'),
        isCurrentMonth: currentDay.month() === currentMonth.month(),
        isToday: currentDay.isSame(dayjs(), 'day'),
        isSelected: currentDay.format('YYYY-MM-DD') === selectedDate
      })
    }
    return days
  }

  // 切换月份
  const handleMonthChange = (direction: 'prev' | 'next') => {
    setCurrentMonth(prev =>
      direction === 'prev'
        ? prev.subtract(1, 'month')
        : prev.add(1, 'month')
    )
  }

  return (
    <View className={classNames(styles.calendar, {
      [styles.expanded]: expanded
    })}
    >
      <View className={styles.header}>
        <View className={styles.title}>
          {expanded ? (
            < >
              <View
                className={styles.monthButton}
                onClick={() => handleMonthChange('prev')}
              >
                <AtIcon value='chevron-left' size='24' color='#12c287' />
              </View>
              <Text className={styles.monthTitle}>
                {currentMonth.format('YYYY年MM月')}
              </Text>
              <View
                className={styles.monthButton}
                onClick={() => handleMonthChange('next')}
              >
                <AtIcon value='chevron-right' size='24' color='#12c287' />
              </View>
            </>
          ) : (
            <Text className={styles.monthTitle}>
              {currentMonth.format('YYYY年MM月')}
            </Text>
          )}</View>

        <View className={styles.rightControls}>


          <View
            className={styles.expandButton}
            onClick={() => setExpanded(!expanded)}
          >
            <Image
              src={expandDown}
              className={`${styles.expandIcon} ${expanded ? styles.rotated : ''}`}
            />
          </View>
        </View>
      </View>

      {expanded ? (
        <View className={styles.monthView}>
          <View className={styles.weekHeader}>
            {['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'].map(weekday => (
              <Text key={weekday} className={styles.weekdayLabel}>{weekday}</Text>
            ))}
          </View>
          <View className={styles.monthDaysContainer}>
            {generateMonthDays().map(day => (
              <View
                key={day.date}
                className={classNames(styles.dayItem, {
                  [styles.selected]: day.isSelected,
                  [styles.todayOutline]: day.isToday,
                  [styles.grayed]: !day.isCurrentMonth
                })}
                onClick={() => onDateSelect(day.date)}
              >
                <Text className={styles.day}>{day.day}</Text>
              </View>
            ))}
          </View>
        </View>
      ) : (
        <View className={styles.weekView}>
          {generateWeekDays().map(day => (
            <View
              key={day.date}
              className={classNames(styles.dayItem, {
                [styles.selected]: day.isSelected,
                [styles.todayOutline]: day.isToday
              })}
              onClick={() => onDateSelect(day.date)}
            >
              <Text className={styles.weekday}>{day.weekday}</Text>
              <Text className={styles.day}>{day.day}</Text>
            </View>
          ))}
        </View>
      )}
    </View>
  )
}

export default Calendar